package com.chb.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author: 陈海彬
 * @date: Created in 2023/9/16 14:50
 * @description: 全局拦截器
 * @modified By:
 * @version: 1.0
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  放行静态资源
        StringBuffer url = request.getRequestURL();
        if (isStatic(url)) {
            return true;
        } else {
            //  判断用户是否登录成功
            Object user = request.getSession().getAttribute("staff");
            if (user != null) {
                return true;
            }
            response.sendRedirect("/login.jsp");
            return false;
        }
    }

    private boolean isStatic(StringBuffer url) {
        boolean result = false;
        String[] arr = {  // 设置放行资源
                "/static", "/login"
        };
        for (String a : arr) {
            if (url.indexOf(a) != -1) {
                result = true;
            }
        }
        return result;
    }

}